package com.tenebrous.jestic.service.framwork.meber.organ;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tenebrous.jestic.entity.framwork.meber.organ.OrgRoster;
import com.tenebrous.jestic.entity.framwork.meber.organ.OrgRosterHistory;
import com.tenebrous.jestic.entity.framwork.meber.organ.OrgUser;
import com.tenebrous.jestic.mapper.idao.framwork.meber.organ.OrgRosterHistoryMapper;
import com.tenebrous.jestic.mapper.idao.framwork.meber.organ.OrgRosterMapper;
import com.tenebrous.jestic.mapper.idao.framwork.meber.organ.OrgUserMapper;
import com.tenebrous.jestic.service.SuperService;
import com.rain.ops.sdk.dto.ApiResult;
import com.rain.ops.sdk.utils.UUIDUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OrgRosterService extends SuperService<OrgRoster> {

    @Autowired
    private OrgRosterHistoryMapper hismapper;

    @Autowired
    private OrgUserMapper userMapper;

    @Autowired
    private OrgRosterMapper mapper;

    @Override
    @Autowired
    protected void setSuperMapper() {
        super.setSuperMapper(this.mapper);
    }

    public OrgRosterHistory getRosterHistoryItem(String hisid) {
        return this.hismapper.selectByPrimaryKey(hisid);
    }

    public OrgRosterHistory getDefultRosterHistoryItem() {
        OrgRosterHistory cdn = new OrgRosterHistory();
        cdn.setStype("标准名册");
        cdn.setActived(1);
        OrgRosterHistory item = this.hismapper.selectOne(cdn);
        if (item == null) {
            List<OrgRosterHistory> list = this.hismapper.selectByCondition("标准名册");
            if (list.size() > 0) {
                item = list.get(0);
            }
        }
        return item;
    }

    /**
     * 查询标准名册
     *
     * @param hisid
     * @return
     */
    public List<OrgRoster> queryStandardList(String hisid) {
        return this.mapper.selectStandardList(hisid, null, null, null, null, null, null, null);
    }

    /**
     * 查询标准名册
     *
     * @param hisid
     * @return
     */
    public List<OrgRoster> queryStandardList(String hisid, String[] companyids, String departmentid, String politiCode, String edutionCode, String degreeCode, String sexCode, String realname) {
        return this.mapper.selectStandardList(hisid, companyids, departmentid, politiCode, edutionCode, degreeCode, sexCode, realname);
    }

    public PageInfo queryStandardPagingList(Integer pageIndex, Integer pageSize, String hisid, String[] companyids, String departmentid, String politiCode, String edutionCode, String degreeCode, String sexCode, String realname) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> this.mapper.selectStandardList(hisid, companyids, departmentid, politiCode, edutionCode, degreeCode, sexCode, realname));
    }

    public List<OrgRosterHistory> queryHistoryList() {
        return this.hismapper.selectAll();
    }

    public PageInfo queryHistoryPagingList(Integer pageIndex, Integer pageSize, String stype) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> this.hismapper.selectByCondition(stype));
    }

    /**
     * 新建标准名册
     *
     * @param item
     * @param ouser
     * @return
     */
    @Transactional
    public ApiResult newasStandard(OrgRosterHistory item, OrgUser ouser) {
        if (Integer.valueOf(1).equals(item.getActived())) {
            this.updateStandardActive(0);
        }
        if (StringUtils.isNotBlank(item.getId())) {
            item.setUpdateDate(new Date());
            item.setUpdateUserid(ouser.getId());
            this.hismapper.updateByPrimaryKeySelective(item);
            return new ApiResult(200, "新建名册成功。", item);
        } else {
            item.setId(UUIDUtils.randomUUID());
            item.setCreateDate(new Date());
            item.setCreateUserid(ouser.getId());
            item.setStype("标准名册");
            this.hismapper.insertSelective(item);
            return new ApiResult(200, "新建名册成功。", item);
        }
    }

    /**
     * 标准名册另存为
     *
     * @param item  名称记录
     * @param hisid 人员集合
     * @param ouser 当前登陆用户
     * @return
     */
    @Transactional
    public ApiResult saveasStandard(OrgRosterHistory item, String hisid, OrgUser ouser) {
        Date dt = new Date();
        OrgRosterHistory hitem = this.hismapper.selectByPrimaryKey(hisid);
        if (hitem != null) {
            if (Integer.valueOf(1).equals(item.getActived())) {
                this.updateStandardActive(0);
            }
            hitem.setId(UUIDUtils.randomUUID());
            hitem.setRemark(item.getRemark());
            hitem.setName(item.getName());
            hitem.setCreateDate(dt);
            hitem.setCreateUserid(ouser != null ? ouser.getId() : null);
            this.hismapper.insertSelective(hitem);

            List<OrgRoster> rlist = this.queryStandardList(hisid);
            for (OrgRoster oitem : rlist) {
                oitem.setCreateDate(dt);
                oitem.setHisid(hitem.getId());
                oitem.setId(UUIDUtils.randomUUID());
                oitem.setCreateUserid(ouser != null ? ouser.getId() : null);
                this.mapper.insertSelective(oitem);
            }
            return new ApiResult(200, "保存成功。", item);
        } else {
            return new ApiResult(999, "未找到指定名称。");
        }
    }

    @Transactional
    public int updateHistorySelective(List<OrgRosterHistory> list) {
        for (OrgRosterHistory item : list) {
            this.hismapper.updateByPrimaryKeySelective(item);
        }
        return list.size();
    }

    @Transactional
    public ApiResult addStandardUser(String hisid, String[] userids, OrgUser ouser) {
        int addcnt = 0;
        int exsitcnt = 0;
        Date dt = new Date();
        OrgRosterHistory hitem = this.hismapper.selectByPrimaryKey(hisid);
        if (hitem != null) {
            for (int i = 0; i < userids.length; i++) {
                OrgUser ou = this.userMapper.selectById(userids[i]);
                if (ou != null) {
                    OrgRoster ritem = this.hismapper.getByHisidAndUserid(hitem.getId(), ou.getId());
                    if (ritem == null) {
                        ritem = new OrgRoster();
                        BeanUtils.copyProperties(ou, ritem, "id", "sort", "createDate", "createUserid", "updateDate", "updateUserid");
                        ritem.setId(UUIDUtils.randomUUID());
                        ritem.setSort(dt.getTime() + i);
                        ritem.setUserid(ou.getId());
                        ritem.setHisid(hisid);
                        ritem.setCreateDate(dt);
                        ritem.setCreateUserid(ouser != null ? ouser.getId() : null);
                        this.mapper.insertSelective(ritem);
                        addcnt++;
                    } else {
                        exsitcnt++;
                    }
                }
            }
            return new ApiResult(200, String.format("更新成功，共选择了%d条记录，其中已存在%d条记录,新增了%d条记录。", userids.length, exsitcnt, addcnt), hitem);
        } else {
            return new ApiResult(999, "添加人员失败，未找到指定名册。");
        }
    }

    @Transactional
    public ApiResult updateStandardUser(String hisid, OrgUser ouser) {
        Date dt = new Date();
        List<OrgRoster> list = this.queryStandardList(hisid);
        for (OrgRoster item : list) {
            OrgUser ou = this.userMapper.selectById(item.getUserid());
            if (ou != null) {
                BeanUtils.copyProperties(ou, item, "id", "sort", "createDate", "createUserid", "updateDate", "updateUserid");
                item.setUpdateDate(dt);
                item.setUpdateUserid(ouser != null ? ouser.getId() : null);
                this.mapper.updateByPrimaryKeySelective(item);
            }
        }
        return new ApiResult(200, String.format("更新成功，共影响了%d条记录。", list.size(), list.size()));
    }

    @Transactional
    public int deleteHistoryByIds(String[] hisids) {
        for (String hisid : hisids) {
            this.mapper.deleteByHisid(hisid);
            this.hismapper.deleteByPrimaryKey(hisid);
        }
        return 1;
    }

    /**
     * 清空名册成员
     *
     * @param hisid
     * @return
     */
    @Transactional
    public int clearByHisid(String hisid) {
        this.mapper.deleteByHisid(hisid);
        return 1;
    }

    public int saveHistorySelective(OrgRosterHistory item) {
        return this.hismapper.insertSelective(item);
    }

    /**
     * 更新标准名册的激活状态
     *
     * @param active
     * @return
     */
    @Transactional
    public int updateStandardActive(Integer active) {
        int i = 0;
        OrgRosterHistory cdn = new OrgRosterHistory();
        cdn.setStype("标准名册");
        List<OrgRosterHistory> hlist = this.hismapper.select(cdn);
        for (OrgRosterHistory hisitem : hlist) {
            hisitem.setActived(0);
            i += this.hismapper.updateByPrimaryKeySelective(hisitem);
        }
        return i;
    }
}
